package com.ebupt.migu.music.global.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.ebupt.migu.globalpopup.entity.*;
import com.ebupt.migu.music.common.auth.IDAuthUtils;
import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.EasyExcelUtil;
import com.ebupt.migu.music.common.util.ExcelUtils;
import com.ebupt.migu.music.common.util.ReqestParamUtil;
import com.ebupt.migu.music.common.util.excelSheet.Sheet;
import com.ebupt.migu.music.global.dto.PriorityRequestBean;
import com.ebupt.migu.music.global.dto.RateMonitor;
import com.ebupt.migu.music.global.service.GlobalActionService;
import com.ebupt.migu.music.global.vo.PopupExportVo;
import com.ebupt.migu.music.global.vo.PopupSummaryExportVo;
import com.ebupt.migu.music.global.vo.PopupVo;
import com.ebupt.migu.music.system.entity.SysUser;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author liuyangyang@ebupt.com
 * @Description
 * @Date 2021/11/23 10:03
 */
@Slf4j
@RestController
@RequestMapping("/global/action")
public class GlobalActionController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private GlobalActionService globalActionService;
    @Autowired
    private IDAuthUtils idAuthUtils;

    private static String[] columnsMinArr = {"createTime", "activityId", "activityName", "realityCntsD",
        "exposureTimesD", "exposureCntsD", "clickTimesD", "clickCntsD", "closeTimesD", "closeCntsD", "realityCntsM",
        "exposureTimesM", "exposureCntsM", "clickTimesM", "clickCntsM", "closeTimesM", "closeCntsM"};
    private static String[] headMinArr = {"数据日期", "活动ID", "活动名称", "实际下发人数", "曝光次数", "曝光人数", "点击次数", "点击人数", "关闭次数",
        "关闭人数", "累计实际下发人数", "累计曝光次数", "累计曝光人数", "累计点击次数", "累计点击人数", "累计关闭次数", "累计关闭人数"};

    /**
     * 创建
     *
     * @param bean
     * @return
     */
    @RequestMapping("/create")
    public ResultObject create(@RequestBody GlobalActionRequestBean bean) {
        SysUser user = ReqestParamUtil.userInfo(request);
        bean.getActivity().setCreatorId(user.getLoginName());
        bean.getActivity().setCreatorName(user.getUserName());
        bean.getActivity().setCreatorDepartment(user.getDeptName());
        return globalActionService.create(user, bean);
    }

    /**
     * 验重
     * 
     * @param bean
     * @return
     */
    @PostMapping("/isHasAds")
    public Boolean isHasAds(@RequestBody GlobalActionRequestBean bean) {
        return globalActionService.isHasAds(bean);
    }

    /**
     * 查询
     *
     * @param bean
     * @return
     */
    @RequestMapping("/select")
    public ResultObject select(@RequestBody QueryGlobalActionsRequestBean bean) {
        SysUser user = ReqestParamUtil.userInfo(request);
        return globalActionService.select(user, bean);
    }

    /**
     * 查询
     *
     * @param bean
     * @return
     */
    @RequestMapping("/selectById")
    public ResultObject selectById(@RequestBody QueryGlobalActionsRequestBean bean) {
        return globalActionService.selectById(bean);
    }

    /**
     * 更新
     *
     * @param bean
     * @return
     */
    @RequestMapping("/update")
    public ResultObject update(@RequestBody GlobalActionRequestBean bean) {
        SysUser user = ReqestParamUtil.userInfo(request);
        bean.getActivity().setCreatorId(user.getLoginName());
        bean.getActivity().setCreatorName(user.getUserName());
        bean.getActivity().setCreatorDepartment(user.getDeptName());
        return globalActionService.update(user, bean);
    }

    @RequestMapping("/delete")
    public ResultObject delete(@RequestBody GlobalActionRequestBean bean) {
        SysUser user = ReqestParamUtil.userInfo(request);
        return globalActionService.delete(user, bean);
    }

    /**
     * 查询页面枚举
     *
     * @return
     */
    @PostMapping("/enum/pages")
    public ResultObject<JSONArray> pageEnum(@RequestBody PageEnum pageEnum) {
        return globalActionService.pageEnum(pageEnum);
    }

    /**
     * 调整活动优先级
     *
     * @return
     */
    @RequestMapping("/priority")
    public ResultObject priority(@RequestBody PriorityRequestBean bean) {
        return globalActionService.priority(bean);
    }

    /**
     * 查询文件是否存在 <br>
     * 存在时将文件内容存入redis，返回key；失败时返回错误
     *
     * @return 查询结果
     */
    @PostMapping("/queryFile")
    public ResultObject queryFile() {
        return globalActionService.queryFile(ReqestParamUtil.getParams(request));
    }

    /**
     * 撤回弹窗 <br>
     * 创建弹窗后审批前，提供撤回弹窗选项，撤回后将弹窗状态改为待提审
     *
     * @return 撤回结果
     */
    @PostMapping("/revocation")
    public ResultObject<String> revocation(@RequestBody ActivityInfo activityInfo) {
        // 验证登录账号是否能执行该操作
        if (!idAuthUtils.isCreatorOrAdminOrAuditor(request, activityInfo)) {
            throw new MyException(StatusEnum.OPERATE_LIMITED, "用户无权撤回此活动");
        }
        // 获取登录用户信息
        SysUser user = ReqestParamUtil.userInfo(request);
        activityInfo.setRevocationId(user.getLoginName());
        activityInfo.setRevocationName(user.getUserName());
        activityInfo.setRevocationDepartment(user.getDeptName());

        return globalActionService.revocation(activityInfo);
    }

    /**
     * 效果统计：分页、条件查询 <br>
     * 查询条件：创建时间段、活动名称、执行类型、目标人群
     *
     * @return 查询结果
     */
    @PostMapping("/queryMap")
    public ResultObject<Page<PopupVo>> queryMap() {
        // 获取查询参数
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        // 验证当前账户权限
        params = idAuthUtils.isAdmin(params);
        return globalActionService.queryMap(params);
    }

    /**
     * 效果统计活动详情
     * 
     * @return 查询结果
     */
    @PostMapping("/qryByIdAndTime")
    public ResultObject qryByIdAndTime() {
        // 获取查询参数
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        // 验证当前账户权限
        params = idAuthUtils.isAdmin(params);
        return globalActionService.qryByIdAndTime(params);
    }

    /**
     * 查询条件： 开始时间、结束时间、策略名称 全量导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMap", produces = MediaType.TEXT_HTML_VALUE)
    public void exportMap() {
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        params = idAuthUtils.isAdmin(params);
        List<PopupExportVo> list = globalActionService.exportMap(params);
        EasyExcelUtil.export(response,
            "1".equals(params.get("summary").toString()) ? PopupSummaryExportVo.class : PopupExportVo.class, list,
            "弹窗运营");
    }

    /**
     * 实时效果统计：分页、条件查询 <br>
     * 查询条件：创建时间段、活动名称、执行类型、目标人群
     *
     * @return 查询结果
     */
    @PostMapping("/queryMinMap")
    public ResultObject<Page<Map<String, Object>>> queryMinMap() {
        // 获取查询参数
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        // 验证当前账户权限
        params = idAuthUtils.isAdmin(params);
        return globalActionService.queryMinMap(params);
    }

    /**
     * 实时查询条件： 开始时间、结束时间、策略名称 全量导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMinMap", produces = MediaType.TEXT_HTML_VALUE)
    public void exportMinMap() {
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        params = idAuthUtils.isAdmin(params);
        List<HashMap<String, Object>> list = globalActionService.exportMinMap(params);
        ExcelUtils excel = new ExcelUtils();
        excel.setName("global_stats_operation").setVersion("2007");// excel 2007's name
        Sheet sheet = new Sheet();
        sheet.setName("变色龙实时运营");// sheet's name
        sheet.setHead(headMinArr);
        sheet.fillData2(list, columnsMinArr);
        excel.addSheet(sheet);
        excel.zipAndResponse(response, request);
    }

    /**
     * 变色龙实时数据可视化试图
     * 
     * @return
     */
    @PostMapping("/queryMinVisualViews")
    public ResultObject queryMinVisualViews() {
        // 获取查询参数
        Map<String, Object> params = ReqestParamUtil.getParamsWithUserInfo(request);
        return globalActionService.queryMinVisualViews(params);
    }

    /**
     * 暂停活动
     *
     * @param activityInfo 活动信息
     * @return 操作结果
     */
    @PostMapping("/pause")
    public ResultObject<String> pauseActivity(@RequestBody ActivityInfo activityInfo) {
        // 验证登录账号是否能执行该操作
        if (!idAuthUtils.isCreatorOrAdminOrAuditor(request, activityInfo)) {
            throw new MyException(StatusEnum.OPERATE_LIMITED, "用户无权暂停此活动");
        }
        return globalActionService.pauseActivity(activityInfo);
    }

    /**
     * 恢复活动
     *
     * @param activityInfo 活动信息
     * @return 操作结果
     */
    @PostMapping("/recovery")
    public ResultObject<String> recoveryActivity(@RequestBody ActivityInfo activityInfo) {
        // 验证登录账号是否能执行该操作
        if (!idAuthUtils.isCreatorOrAdminOrAuditor(request, activityInfo)) {
            throw new MyException(StatusEnum.OPERATE_LIMITED, "用户无权恢复此活动");
        }
        return globalActionService.recoveryActivity(activityInfo);
    }

    /**
     * 变色龙全局弹窗设置
     * 
     * @return 操作结果
     */
    @PostMapping("/frequency")
    public ResultObject<String> frequency(@RequestBody ActivityFrequency frequencyMap) {
        // 验证登录账号是否能执行该操作
        SysUser user = ReqestParamUtil.userInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("cid", user.getId());
        Map<String, Object> rights = idAuthUtils.isAdmin(params);
        if (rights.get("isAdmin").equals("0") && rights.get("isSuperAdmin").equals("0")) {
            throw new MyException(StatusEnum.OPERATE_LIMITED, "用户无权操作全局配置开关");
        }
        return globalActionService.frequency(frequencyMap);
    }

    /**
     * 获取变色龙全局弹窗状态
     * 
     * @return 操作结果
     */
    @PostMapping("/getfreStatus")
    public ResultObject<String> getfreStatus() {
        return globalActionService.getfreStatus();
    }

    /**
     * 根据创建人，查询上一次的转化率阈值监控配置
     *
     * @param creator
     * @return
     */
    @PostMapping("/qrySettingsByCreator")
    public ResultObject<HashMap<String, Object>> qrySettingsByCreator(@RequestParam String creator) {
        return globalActionService.qrySettingsByCreator(creator);
    }

    @PostMapping("/upsertSettings")
    public ResultObject<HashMap<String, Object>> upsertSettings(@RequestBody RateMonitor monitor) {
        return globalActionService.upsertSettings(monitor);
    }

}